package com.cc.controller.common;

import com.cc.base.ResponseResult;
import com.cc.exception.BusinessException;
import com.cc.utils.AliYunOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@RestController
@RequestMapping("/common/file")
@ResponseBody
@Slf4j
@Tag(name = "文件相关")
public class FileController {
    @Autowired
    private AliYunOssUtils aliYunOssUtils;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @Operation(summary = "图片文件上传")
    public ResponseResult<String> upload(MultipartFile file) throws Exception {
        if (file==null){
           throw new BusinessException(500,"上传文件不能为空");
        }
        // 校验是否为图片文件
        if (file.getSize() == 0) {
            throw new BusinessException(500,"上传图片不能为空");
        }
        // 获得原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获得文件扩展名
        String extension = null;
        if (originalFilename != null) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + extension;

        String filePath = aliYunOssUtils.uploadFile(fileName, file.getInputStream());
        return ResponseResult.ok(filePath);
    }
}
